import React, { useEffect, useState } from 'react'
import type { DrawerProps } from 'antd'
import type { FormProps } from 'antd'
import { Button, Form, Input, Drawer, Select, Radio, message } from 'antd'

import {
  reqSnowId,
  reqGoodsTypesList,
  reqGoodDetailById,
  reqCreateGood,
  type GoodType
} from '@/api/good'
import { reqBrandList, type Brand, type ApiResponse } from '@/api/brand'
import MyUpload from '@/components/MyUpload'
import MyEditor from '@/components/MyEditor'

const { TextArea } = Input

type FieldType = {
  id?: number
  goodsCode?: string
  goodsName?: string
  bId?: number
  gtId?: number
  price?: number
  photo?: string
  state?: number
  remark?: string
  desc?: string
}

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo)
}

//--------------------商品添加----------------------//
const GoodDraw: React.FC = (props: any) => {
  let [form] = Form.useForm()
  let [title, setTitle] = useState<string>('商品添加')
  let [placement] = useState<DrawerProps['placement']>('right')
  let [photo, setPhoto] = useState<string>()
  let [brandList, setBrandList] = useState<Brand[]>()
  let [goodTypeList, setGoodTypeList] = useState<GoodType[]>()
  let [goodsCode, setGoodsCode] = useState<string>()
  let [htmlContent, setHtmlContent] = useState<string>()
  let initialValues = {
    id: 0,
    bid: '请选择', // 对应 Form.Item 的 name
    gtid: '请选择',
    state: true,
    goodsCode: '',
    goodsName: '',
    price: '',
    photo: '',
    remark: '',
    desc: ''
  }

  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    console.log('Success:', values)
    // 在这里可以进行表单提交的操作
    let obj = {
      id: props.id,
      ...values
    }
    let res: any = await reqCreateGood(obj)
    if (res.data > 0) {
      message.success('操作成功')
      //关闭抽屉
      onClose()
      //触发父组件的刷新数据
      // if (props.onRefresh) {
      //   props.onRefresh();
      // }
    }
  }

  //关闭抽屉
  const onClose = () => {
    //清空表单+关闭抽屉
    form.resetFields()
    setPhoto(undefined)
    setHtmlContent(undefined)

    //子向父组件传递数据
    if (props.onClose) {
      props.onClose(false, null, true)
    }
  }

  useEffect(() => {
    getBrandList()
    getGoodsTypesList()
    getGoodsCode()
  }, [])

  useEffect(() => {
    console.log(props.id)
    if (props.id > 0) {
      // 确保 title 状态为字符串类型，原代码中 title 初始化为布尔值，这里需要修正
      if (typeof props.id === 'number') {
        setTitle(props.id > 0 ? '编辑商品' : '添加商品')
      } else {
        console.warn('props.id 不是一个数字类型，无法正确设置标题')
      }
      //发送请求获取商品信息
      reqGoodDetailById(props.id).then((res: any) => {
        form.setFieldsValue(res.data)
        setPhoto(res.data.photo)
        setHtmlContent(res.data.desc)
      })
    } else {
      setTitle('添加商品')
      getGoodsCode()
    }
  }, [props.id])

  //获取商品编号
  const getGoodsCode = async () => {
    const res: any = await reqSnowId()
    setGoodsCode(res.data)
    form?.setFieldsValue({ goodsCode: res.data })
  }

  //获取品牌列表
  const getBrandList = async () => {
    const res: ApiResponse<Brand[]> = await reqBrandList()
    console.log(res)
    const list = res.data.map((item) => {
      return {
        value: item.id,
        label: item.bName
      }
    })
    setBrandList(list as unknown as Brand[])
    console.log(brandList)
  }
  //获取商品类型列表
  const getGoodsTypesList = async () => {
    const res = await reqGoodsTypesList()
    console.log(res)
    if (Array.isArray(res.data)) {
      const list = res.data.map((item: GoodType) => {
        return {
          value: item.id,
          label: item.goodsTypeName
        }
      })
      setGoodTypeList(list as unknown as GoodType[])
      // console.log(goodTypeList)
    }
  }

  //图片上传 子组件向父组件传递数据
  const onUploadSuccess = (file: any) => {
    // console.log(file)
    form.setFieldsValue({ photo: file })
  }
  //富文本编辑器 子组件向父组件传递数据
  const handleEditorChange = (value: string) => {
    // console.log(value)
    form.setFieldsValue({ desc: value })
  }
  return (
    <>
      <Drawer
        title={title}
        placement={placement}
        width={700}
        onClose={onClose}
        open={props.open}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          style={{ maxWidth: 600 }}
          initialValues={initialValues}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="商品编号" name="goodsCode">
            <Input disabled value={goodsCode} />
          </Form.Item>

          <Form.Item<FieldType>
            label="商品名称"
            name="goodsName"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="商品品牌"
            name="bId"
            rules={[{ required: true, message: '请选择商品品牌!' }]}
          >
            <Select
              style={{ width: 120 }}
              allowClear
              options={brandList}
              placeholder="请选择"
            />
          </Form.Item>
          <Form.Item<FieldType>
            label="商品分类"
            name="gtId"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select
              style={{ width: 120 }}
              allowClear
              options={goodTypeList}
              placeholder="请选择"
            />
          </Form.Item>
          <Form.Item<FieldType>
            label="商品价格"
            name="price"
            rules={[
              { required: true, message: '请输入商品价格' },
              { pattern: /^[1-9]\d*(\.\d+)?$/i, message: '只能输入正数' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="商品图片"
            name="photo"
            rules={[{ required: true, message: '请选择图片!' }]}
          >
            <MyUpload onUploadChange={onUploadSuccess} photo={photo}></MyUpload>
          </Form.Item>

          <Form.Item<FieldType>
            label="商品状态"
            name="state"
            initialValue={true}
            rules={[{ required: true, message: '请选择商品状态!' }]}
          >
            <Radio.Group
              options={[
                { value: true, label: '上架' },
                { value: false, label: '下架' }
              ]}
            />
          </Form.Item>

          <Form.Item<FieldType>
            label="商品说明"
            name="remark"
            rules={[{ required: true, message: '请输入商品名称!' }]}
          >
            <TextArea rows={3} placeholder="请输入商品说明" maxLength={6} />
          </Form.Item>
          <Form.Item<FieldType>
            label="商品详情"
            name="desc"
            // rules={[{ required: true, message: '请输入商品详情' }]}
          >
            <MyEditor
              htmlContent={htmlContent}
              onEditorChange={handleEditorChange}
            ></MyEditor>
          </Form.Item>
          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
            <Button type="default" onClick={onClose}>
              关闭
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}

export default GoodDraw
